package com.xfcycle.zebrabikegp.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.vise.baseble.callback.IConnectCallback;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.core.DeviceMirror;
import com.vise.baseble.exception.BleException;
import com.vise.baseble.model.BluetoothLeDeviceStore;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.AlarmAssist;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.AlarmInfoResult;
import com.xfcycle.zebrabikegp.bean.BikeInfoResult;
import com.xfcycle.zebrabikegp.bean.UserInfoByUidResult;
import com.xfcycle.zebrabikegp.constant.ActivityChangeConstant;
import com.xfcycle.zebrabikegp.constant.AlarmConstant;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.TimingConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.dto.ScanDeviceConditionsDTO;
import com.xfcycle.zebrabikegp.listener.OnTimeOutListener;
import com.xfcycle.zebrabikegp.map.CustomLocationUtil;
import com.xfcycle.zebrabikegp.util.ActivitiesStackUtil;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xfcycle.zebrabikegp.util.MapNavigationUtil;
import com.xfcycle.zebrabikegp.util.TimingThreadUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地图主页面
 *
 * @author xFcycle 2017年4月26日
 */
public class HomeMapActivity extends RootActivity {

    private Gson gson = new Gson();

    //地图相关信息
    public GoogleMap mMap;
    private LocationManager locationManager;
    private Location myLocation;
    private Double latitude;
    private Double longitude;

    private View ic_control_bike_menu;
    private View ic_add_bike_menu;

    private ImageView iv_user_log;
    private ImageView iv_person;
    private TextView tv_alarm_prompt;
    private ImageView iv_bike;
    private ImageView iv_bike_my_location;
    private ImageView iv_bike_bike_location;
    private ImageView iv_menu;
    private ImageView iv_search;
    private ImageView iv_home_status;
    private ImageView iv_home_connect;
    private ImageView iv_home_lock;
    private ImageView iv_bike_connect_status;

    private TextView tv_home_lock_status;

    private TextView tv_home_connect_status;
    private TextView tv_bike_name;
    private TextView tv_bike_state;

    private TextView tv_um_username;
    private TextView tv_um_email_address;

    private RelativeLayout rl_cover;
    private LinearLayout ll_map_mask;
    private LinearLayout ll_bike_status_menu;
    private LinearLayout ll_home_status_eco;
    private LinearLayout ll_home_status_smt;
    private ImageView iv_home_status_bike;
    private ImageView iv_home_status_smt;
    private ImageView iv_home_status_eco;
    private ImageView iv_home_status_pow;

    private RelativeLayout rl_add_bike;
    private RelativeLayout rl_user_simple_info;
    private RelativeLayout rl_user_menu_sport;
    private RelativeLayout rl_device_menu;
    private RelativeLayout rl_user_menu_myBike;
    private RelativeLayout rl_user_menu_about;
    private RelativeLayout rl_user_menu_setting;
    private RelativeLayout rl_user_menu_debug;

    //仪表盘相关
    private ImageView iv_dashboard_state;
    private LinearLayout ll_dashboard;

    private SupportMapFragment mapFragment;

    //车电量相关
    private TextView tv_bike_electric_amount;
    private ProgressBar pb_bike_electricity;

    private DrawerLayout drawer;

    private HandleDataByBLEUtil handleDataByBLEUtil;
    private ScanDeviceConditionsDTO scanDeviceConditionsDTO;

    //ListView相关对象
    private ListView lv_search_bike_result;
    private BikeInfoAdapter bikeInfoAdapter;
    private BikeInfoResult[] bikeInfoResults;
    private List<BikeInfoResult> bikeInfoList;

    private StringBuffer deviceNameSb;
    //地图标识Map集合
    private Map<String, Marker> bikeMarkersMap;
    private LatLng markLatLng;

    //点击的自行车图标的名称 防止误连
    private String showMarkerKey;
    //当前点击的自行车标识
    private String[] currentDeviceInfos = new String[2];

    //已搜索到的设备名称
    private String scanMarkerKey;
    //当前连接的设备名称,避免重复连接等一系列动作
    public String connectMarkerKey;
    private String currentConnectBikeId;

    private final static String TAG = "HomeMapActivity";
    //控制自行车菜单栏是否展示
    private boolean ic_control_bike_menu_display_status = false;

    //添加自行车菜单栏是否展示
    private boolean ic_add_bike_menu_display_status = false;
    //自行车助力状态是否展示，B S E P
//    private boolean bike_status = true;

    //侧滑屏是否在展示
    private boolean drawer_show = false;

    private HomeMapHandleDataFromBleReceiver homeMapHandleDataFromBleReceiver;
    private HomeMapAlarmMessageReceiver homeMapAlarmMessageReceiver;

    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    private double firstPressTime;

    private Bundle bundle;
    private String uid;

    private TimingThreadUtil elecTimingThreadUtil;
    private TimingThreadUtil locationTimingThreadUtil;
    private TimingThreadUtil connectTimingThreadUtil;
    private Integer connectNum = 0;

    //当前手机所在经纬度信息
    private Location currentLocation;

    //用户名下所有蓝牙信息
    private Map<String, String> bikeInfos;

    //判断查询的车锁状态是在连接车辆发送验证码之后还是查询电量之后
    private boolean isBatteryAfterLock = false;

    //改变车辆连接提示框
    private AlertDialog changeBikeConnectDialog;

    //上传到服务器的车辆信息
//    private String bikeBattery;
//    private String bikeGear;
//    private String bikeLock;

    //报警信息辅助类
    private AlarmAssist alarmAssist;

    //连接回调
    private IConnectCallback iConnectCallback;
    //搜索回调
    private IScanCallback iScanCallback;
    //判断连接设备是否改变
    private boolean isDeviceNotChange = false;

    private String historyConnectBikeName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_map);

        bundle = this.getIntent().getExtras();

        initView();
        initChangeBikeConnectDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewListener();

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, 10 * 1000);

        //用户数据未更新
        if ("----------".equals(tv_um_email_address.getText().toString())) {
            initViewContent();
        }

        //展示用户头像
        showUserPortrait();

        //注册从蓝牙设备接收数据广播
        homeMapHandleDataFromBleReceiver = new HomeMapHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(homeMapHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);

        //注册接收报警车辆广播
        homeMapAlarmMessageReceiver = new HomeMapAlarmMessageReceiver();
        registBroadcastReceiverAtActivity(homeMapAlarmMessageReceiver, BluetoothDeviceConstant.ALARM_MESSAGE_BROADCAST_RECEIVER_ACTION);

        //判断有没有被主动断开
        if (!BlueToothAssist.isConnect) {
            connectMarkerKey = "";
            currentConnectBikeId = "";
            BlueToothAssist.connectDeviceName = "";
            BlueToothAssist.currentConnectBikeId = "";
            closeControlBikeMenu();
            closeBikeListMenu();
        }

        //判断是否在别的窗体接收到报警信息
        if(AlarmAssist.isAlarm){
            AlarmAssist.isAlarm = false;
            //查询用户名下所有自行车
            new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO_BY_ALARM, HomeMapActivity.this).start();
        }

        //判断是否有报警信息
        if(alarmAssist.isAlarmExist() && View.GONE == tv_alarm_prompt.getVisibility()){
            tv_alarm_prompt.setVisibility(View.VISIBLE);
        }

        //若车锁已打开 开启查询电量定时器
        if (BlueToothAssist.isUnlock) {
            elecTimingThreadUtil.openThread(TimingConstant.ELECTRIC_THREAD_NAME, TimingConstant.ELECTRIC_TIME);
        }

        //查询历史车辆连接名称
        historyConnectBikeName = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, SpConstant.HISTORY_CONNECT_BIKE_NAME_KEY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        connectNum = 0;
        if (null != homeMapHandleDataFromBleReceiver) {
            //注销蓝牙信息广播
            unregisterReceiver(homeMapHandleDataFromBleReceiver);
        }

        if (null != homeMapAlarmMessageReceiver) {
            //注销警告信息广播
            unregisterReceiver(homeMapAlarmMessageReceiver);
        }

        //若车锁已打开 关闭查询电量定时器
        if (BlueToothAssist.isUnlock) {
            elecTimingThreadUtil.closeThread(TimingConstant.ELECTRIC_THREAD_NAME);
        }
    }
    /***********************************************************************************************/
    /**                                 Google Map相关方法                                         **/
    /***********************************************************************************************/

    /**
     * 地图回调方法
     *
     * @param googleMap
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        //确定已获得权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        //获得位置信息提供者
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //开启GPS
        openGPSSettings();

        //获得定位信息
        for (String provider : locationManager.getProviders(true)) {
            myLocation = locationManager.getLastKnownLocation(provider);
            if (null != myLocation) {
                break;
            }
        }

        mMap = googleMap;

        //展示自身位置小蓝点
        mMap.setMyLocationEnabled(true);
        //隐藏定位按钮
        mMap.getUiSettings().setMyLocationButtonEnabled(false);

        if (null == myLocation) {
            LatLng initLatLng = new LatLng(32.05, 118.8);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initLatLng, 14));
            return;
        }

        //经度
        longitude = myLocation.getLongitude();
        //纬度
        latitude = myLocation.getLatitude();

        //设置程序启动时经纬度定位,先纬度，后经度
        LatLng myLatLng = new LatLng(latitude, longitude);

        //设置摄像头位置，及地图比列尺大小 数字越小 单屏显示的地理范围越大
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 14));

        //添加自定义图标点击事件
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                marker.showInfoWindow();

                showMarkerKey = marker.getTitle();

                if (showMarkerKey.contains("vt")) {
                    markLatLng = marker.getPosition();
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markLatLng, 18));
                    //展示自行车控制页面
                    openControlBikeMenu(marker.getTitle(), marker.getSnippet());
                }
                return false;
            }
        });

        //自定义地图上Marker图标的 标题栏
        mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                //该标识为导航标识
                if (!marker.getTitle().contains("vt")) {
                    return null;
                }

                ImageView imageView = new ImageView(HomeMapActivity.this);
                // 改变图标为连接
//                if ("conn".equals(tv_home_connect_status.getText().toString())) {
//                    imageView.setImageBitmap(BitmapFactory.decodeResource(HomeMapActivity.this.getResources(), R.drawable.ic_bike_marker_con));
//                }
                //改变图标为锁车
                if ("lock".equals(tv_home_lock_status.getText().toString())) {
                    imageView.setImageBitmap(BitmapFactory.decodeResource(HomeMapActivity.this.getResources(), R.drawable.ic_bike_marker_lock));
                }
                //改变图标为未锁
                if ("unlock".equals(tv_home_lock_status.getText().toString())) {
                    imageView.setImageBitmap(BitmapFactory.decodeResource(HomeMapActivity.this.getResources(), R.drawable.ic_bike_marker_con));
                }
                //改变图标为断开连接
                if ("disc".equals(tv_home_connect_status.getText().toString())) {
                    imageView.setImageBitmap(BitmapFactory.decodeResource(HomeMapActivity.this.getResources(), R.drawable.ic_bike_marker_disc));
                }
                return imageView;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });

        //地图标识长按拖动事件
        mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
            }

            @Override
            public void onMarkerDrag(Marker marker) {
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                marker.setPosition(marker.getPosition());
            }
        });

        //地图标识信息窗口点击事件
        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                //该标识为导航标识
                if (!marker.getTitle().contains("vt")) {
                    jumpOutsideNavigation(marker.getPosition().latitude, marker.getPosition().longitude);
                }
            }
        });
    }

    /**
     * 在地图上添加一个自行车的标识
     */
    private Marker addBikeMarkerToMap(String lat, String lng, String title, String nickName) {
        //设置经纬度数据
        LatLng bikeLocation = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));

        if (null == mMap) {
            Log.e(TAG, "addBikeMarkerToMap: mMap 地图未初始化，无法添加地图标识");
            Toast.makeText(this.getApplicationContext(), ToastConstant.MAP_CAN_NOT_ADD_MARKER, Toast.LENGTH_SHORT).show();
            return null;
        }

        //添加地图标识，并返回
        Marker bikeMarker = mMap.addMarker(new MarkerOptions().position(bikeLocation).title(title).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike_marker_find)).snippet(nickName));

        return bikeMarker;
    }

    /**
     * 判断GPS定位是否打开，如果没打开，则跳转到GPS设置页面
     */
    public void openGPSSettings() {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.OPEN_GPS, Toast.LENGTH_SHORT).show();
            try {
                //跳转到打开页面
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 在地图上添加导航定位标识
     */
    private Marker addMarkerToMap(LatLng location, String title, String snippet) {

        if (null == mMap) {
            Log.e(TAG, "addBikeMarkerToMap: mMap 地图未初始化，无法添加地图标识");
            Toast.makeText(this.getApplicationContext(), ToastConstant.MAP_CAN_NOT_ADD_MARKER, Toast.LENGTH_SHORT).show();
            return null;
        }

        //添加地图标识，并返回
        Marker marker = mMap.addMarker(new MarkerOptions()
                .position(location)
                .title(title)
                .snippet(snippet)
                .draggable(true));
        //标识可被移动
        marker.setDraggable(true);

        //地图镜头跳转
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));
        return marker;
    }

    //跳出外部导航
    private void jumpOutsideNavigation(double latitude, double longitude) {

        if (MapNavigationUtil.isAvailable(getApplicationContext(), "com.google.android.apps.maps")) {

            // 跳转到谷歌地图外部导航
            try {
                Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + "," + longitude + "&mode=b");
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                startActivity(mapIntent);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            Toast.makeText(HomeMapActivity.this.getApplicationContext(), ToastConstant.GOOGLE_MAP_APP_NOT_EXIST, Toast.LENGTH_LONG).show();

            //没有谷歌地图 跳转到应用市场
            try {
                Uri uri = Uri.parse("market://details?id=com.google.android.apps.maps");
                Intent marIntent = new Intent(Intent.ACTION_VIEW, uri);
                HomeMapActivity.this.startActivity(marIntent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    /**
     * 初始化控件
     */
    public void initView() {
        bikeInfos = new HashMap<>();

        ic_control_bike_menu = findViewById(R.id.ic_fg_home_menu);
        ic_add_bike_menu = findViewById(R.id.ic_fg_add_bike_menu);
        iv_user_log = (ImageView) findViewById(R.id.iv_user_log);
        iv_person = (ImageView) findViewById(R.id.iv_person);
        tv_alarm_prompt = (TextView) findViewById(R.id.tv_alarm_prompt);
        iv_bike = (ImageView) findViewById(R.id.iv_bike);
        iv_bike_my_location = (ImageView) findViewById(R.id.iv_bike_my_location);
        iv_bike_bike_location = (ImageView) findViewById(R.id.iv_bike_bike_location);
        iv_menu = (ImageView) findViewById(R.id.iv_menu);
        iv_search = (ImageView) findViewById(R.id.iv_search);

        iv_home_connect = (ImageView) findViewById(R.id.iv_home_connect);
        iv_home_lock = (ImageView) findViewById(R.id.iv_home_lock);
        iv_home_status = (ImageView) findViewById(R.id.iv_home_status);

        iv_bike_connect_status = (ImageView) findViewById(R.id.iv_bike_connect_status);

        tv_home_lock_status = (TextView) findViewById(R.id.tv_lock_status);
        tv_home_connect_status = (TextView) findViewById(R.id.tv_connect_status);

        tv_bike_name = (TextView) findViewById(R.id.tv_bike_name);
        tv_bike_state = (TextView) findViewById(R.id.tv_bike_state);

        tv_um_username = (TextView) findViewById(R.id.tv_um_username);
        tv_um_email_address = (TextView) findViewById(R.id.tv_um_email_address);

        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);
        ll_home_status_eco = (LinearLayout) findViewById(R.id.ll_home_status_eco);
        ll_home_status_smt = (LinearLayout) findViewById(R.id.ll_home_status_smt);
        iv_home_status_bike = (ImageView) findViewById(R.id.iv_home_status_bike);
        iv_home_status_smt = (ImageView) findViewById(R.id.iv_home_status_smt);
        iv_home_status_eco = (ImageView) findViewById(R.id.iv_home_status_eco);
        iv_home_status_pow = (ImageView) findViewById(R.id.iv_home_status_pow);

        ll_map_mask = (LinearLayout) findViewById(R.id.iv_map_mask);
        rl_add_bike = (RelativeLayout) findViewById(R.id.rl_add_bike);
        rl_user_menu_sport = (RelativeLayout) findViewById(R.id.rl_user_menu_sport);
        ll_bike_status_menu = (LinearLayout) findViewById(R.id.ll_bike_status_menu);
        rl_device_menu = (RelativeLayout) findViewById(R.id.rl_device_menu);
        rl_user_menu_myBike = (RelativeLayout) findViewById(R.id.rl_user_menu_mybike);
        rl_user_menu_about = (RelativeLayout) findViewById(R.id.rl_user_menu_about);
        rl_user_menu_setting = (RelativeLayout) findViewById(R.id.rl_user_menu_setting);
        rl_user_menu_debug = (RelativeLayout) findViewById(R.id.rl_user_menu_debug);
        rl_user_simple_info = (RelativeLayout) findViewById(R.id.rl_user_simple_info);

        lv_search_bike_result = (ListView) findViewById(R.id.lv_search_bike_result);

        pb_bike_electricity = (ProgressBar) findViewById(R.id.pb_bike_electricity);
        tv_bike_electric_amount = (TextView) findViewById(R.id.tv_bike_electric_amount);

        iv_dashboard_state = (ImageView) findViewById(R.id.iv_dashboard_state);
        ll_dashboard = (LinearLayout) findViewById(R.id.ll_dashboard);

        deviceNameSb = new StringBuffer();

        drawer = (DrawerLayout) findViewById(R.id.dl_home_page);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, 10 * 1000);

        bikeMarkersMap = new HashMap<>();
        showMarkerKey = new String();
        scanMarkerKey = new String();
        connectMarkerKey = new String();

        alarmAssist = AlarmAssist.getInstance();

        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);

        //获得地图组件
        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fargment_map);
        //开启地图异步任务
        mapFragment.getMapAsync(this);

        //将SimpleAdapter添加到listView中
        bikeInfoList = new ArrayList<>();
        bikeInfoAdapter = new BikeInfoAdapter();
        //自定义ListView适配器
        lv_search_bike_result.setAdapter(bikeInfoAdapter);

        //查询电量定时器
        elecTimingThreadUtil = TimingThreadUtil.getInstance(TimingConstant.ELECTRIC_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                Log.i(TAG, "timeOut: ---------------------------- 查询电量 及锁状态");

                //查询是否锁车
                handleDataByBLEUtil.sendDataToDevice("c|r");
                isBatteryAfterLock = true;
            }
        });

        //连接车辆，上传位置定时器
        locationTimingThreadUtil = TimingThreadUtil.getInstance(TimingConstant.BIKE_LOCATION_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                Log.i(TAG, "timeOut: ---------------------------- 上传位置 ---- 车辆锁状态 " + BlueToothAssist.isUnlock + " ----- 当前连接车辆id " + currentConnectBikeId);
                //车辆已解锁
                if (BlueToothAssist.isUnlock && null != currentConnectBikeId) {

                    //获取当前经纬度位置
                    currentLocation = CustomLocationUtil.obtainCurrentLocation(HomeMapActivity.this);

                    if (null == currentLocation) {
                        Log.i(TAG, "timeOut: 获取到的地理位置为 null");
                        return;
                    }

                    //经度
                    Double tempLongitude = currentLocation.getLongitude();
                    //纬度
                    Double tempLatitude = currentLocation.getLatitude();

                    if(false){
                        //判断当前经纬度位置没有变化 不上传数据
                        if(tempLongitude == longitude && tempLatitude == latitude){
                            return;
                        }
                    }

                    latitude = tempLatitude;
                    longitude = tempLongitude;

                    //上传车辆经纬度到服务器
                    Map<String, String> params = new HashMap<>();
                    params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_LAT, latitude + "");
                    params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_LNG, longitude + "");

                    //电量
//                    params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_LNG, bikeBattery);
                    //档位
//                    params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_LNG, bikeGear);
                    //是否锁车
//                    params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_LNG, bikeLock);

                    new GetJsonFromWebJob(WebConstant.SEND_BIKE_INFO_PATH + currentConnectBikeId, WebConstant.PUT, params, REQUEST_SIGN_CHANGE_BIKE_NICKNAME_BY_CID, HomeMapActivity.this).start();

                    //更新地图图标位置
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Marker marker = bikeMarkersMap.get(connectMarkerKey);
                            if (null == marker) {
                                Log.e(TAG, "timeOut: ------------------ 定时上报位置对应的marker 为null");
                                return;
                            }

                            marker.setPosition(new LatLng(latitude, longitude));
                        }
                    });


                }
            }
        });

        //连接超时监听器
        connectTimingThreadUtil = TimingThreadUtil.getInstance(TimingConstant.CONNECT_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                if (connectNum > 19 && null != connectTimingThreadUtil) {
                    connectTimingThreadUtil.closeThread(TimingConstant.CONNECT_THREAD_NAME);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!BlueToothAssist.isConnect) {
                                Toast.makeText(HomeMapActivity.this.getApplicationContext(), ToastConstant.BLE_CONNECT_TIME_OUT, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
                connectNum++;
            }
        });

        //初始化连接回调
        iConnectCallback = new IConnectCallback() {
            @Override
            public void onConnectSuccess(DeviceMirror deviceMirror) {
                Log.i(TAG, "onConnectSuccess: 连接成功");

                //绑定读写通道
                handleDataByBLEUtil.bindWriteAndReadChannel(deviceMirror);
            }

            @Override
            public void onConnectFailure(BleException exception) {
                Log.i(TAG, "onConnectFailure: 连接失败 被动连接断开 " + exception.getCode() + " " + exception.getDescription());
                try {

                    closeWaitWindow();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setBikeStateDisConnect(connectMarkerKey);

                            //改变蓝牙辅助类参数
//                            BlueToothAssist.isUnlock = false;
//                            BlueToothAssist.isConnect = false;
//                            BlueToothAssist.currentConnectBikeId = null;
//                            connectMarkerKey = "";

                            //清除所有当前正在进行的定时线程
                            TimingThreadUtil.closeAllTiming();
                        }
                    });

                    //判断是否是异常断开
                    if("CONNECT_ERR".equals(exception.getCode().toString())){
                        isDeviceNotChange = true;
                        //异常断开重连搜索
                        repairConnectScan();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDisconnect(boolean isActive) {
                Log.i(TAG, "onDisconnect: 主动断开连接");

                //改变蓝牙辅助类参数
//                BlueToothAssist.isUnlock = false;
//                BlueToothAssist.isConnect = false;
//                BlueToothAssist.currentConnectBikeId = null;

                //清除所有当前正在进行的定时线程
                TimingThreadUtil.closeAllTiming();
            }
        };

        //初始化搜索回调
        iScanCallback = new IScanCallback() {
            @Override
            public void onDeviceFound(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
                Log.i(TAG, "onDeviceFound: 搜索到设备 " + bluetoothLeDeviceStore.getDeviceList().size());
            }

            @Override
            public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
                Log.i(TAG, "onScanFinish: 搜索结束");

                if(null != bluetoothLeDeviceStore.getDeviceMap().get(scanDeviceConditionsDTO.getDeviceAddress())) {
                    Log.i(TAG, "onDeviceFound: 搜索到目标设备");

                    //通过名称连接蓝牙设备
                    handleDataByBLEUtil.connectDeviceByNameWithoutScan(scanDeviceConditionsDTO.getDeviceName(), iConnectCallback);
                }else if(isDeviceNotChange){
                    //再次进入搜索流程
                    repairConnectScan();
                }
            }

            @Override
            public void onScanTimeout() {
                Log.i(TAG, "onDeviceFound: 搜索超时");
            }
        };

        //利用系统功能获取当前所在位置经纬度
        currentLocation = CustomLocationUtil.obtainCurrentLocation(this);
    }

    /**
     * 组件监听事件添加
     */
    public void initViewListener() {
        //地图跳出导航按钮
        iv_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭菜单栏
                closeBikeListMenu();
                closeControlBikeMenu();

                //跳转搜索地点半页面
                try {
                    Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(HomeMapActivity.this);
                    startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
                } catch (Exception e) {
                    Toast.makeText(HomeMapActivity.this.getApplicationContext(), ToastConstant.JUMP_NAVIGATION_ACTIVITY_FAILURE, Toast.LENGTH_SHORT).show();
                }
            }
        });

        //跳转到警报界面
        tv_alarm_prompt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏报警提示
                tv_alarm_prompt.setVisibility(View.GONE);

                //页面跳转到警报界面
                activityChange(ALARM_LIST_ACTIVITY, null, null);
            }
        });

        //快捷打开控制自行车界面
        iv_bike.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != connectMarkerKey) {
                    //移动镜头到当前自行车位置
                    moveCameraToCurrentMark(connectMarkerKey);
                    closeBikeListMenu();
                    //打开控制车辆界面
                    if (!ic_control_bike_menu_display_status && BlueToothAssist.isConnect) {
                        ic_control_bike_menu.setVisibility(View.VISIBLE);
                        ic_control_bike_menu_display_status = true;
                    } else {
                        ic_control_bike_menu.setVisibility(View.GONE);
                        ic_control_bike_menu_display_status = false;
                    }
                }
            }
        });

        //修改摄像头到当前自己所在位置
        iv_bike_my_location.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //获取当前位置
                    currentLocation = CustomLocationUtil.obtainCurrentLocation(HomeMapActivity.this);

                    //移动地图镜头
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), 18));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //跳转到蓝牙搜索页面
        rl_add_bike.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭当前蓝牙连接
                closeBleDevice();

                //页面跳转到搜索页面
                Map<String, String> params = new HashMap<>();
                params.put("bikeInfos", gson.toJson(bikeInfos));
                activityChange(BLUETOOTH_SEARCH_ACTIVITY, params, REQUEST_CODE_BLUETOOTH_SEARCH);
            }
        });

        //添加自行车目录 控制其展开还是收起
        iv_menu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                closeControlBikeMenu();

                if (ic_add_bike_menu_display_status) {
                    closeBikeListMenu();
                    return;
                }

                if (!ic_add_bike_menu_display_status) {
                    openBikeListMenu();
                    return;
                }
            }
        });

        //阻断点击事件传递，防止点击到控制车辆按钮父容器导致面板回缩
        ic_control_bike_menu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        //给图层蒙版添加点击事件，隐藏所有菜单目录
        ll_map_mask.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.w(TAG, "onTouch: ----------------- " + ic_control_bike_menu_display_status + "------" + ic_add_bike_menu_display_status);
                if (ic_control_bike_menu_display_status || ic_add_bike_menu_display_status) {
                    closeBikeListMenu();
                    closeControlBikeMenu();
                }
                return false;
            }
        });

        // 个人信息展示按钮
        iv_person.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (drawer_show) {
                    drawer.closeDrawer(Gravity.START);
                }
                if (!drawer_show) {
                    drawer.openDrawer(Gravity.START);
                }
            }
        });

        //监听左侧滑动栏是否消失
        drawer.setDrawerListener(new DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                drawer_show = !drawer_show;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                drawer_show = !drawer_show;
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });

        //跳转到修改用户信息界面
        rl_user_simple_info.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> params = new HashMap<>();
                params.put("uid", uid);
                activityChange(MY_PROFILE_ACTIVITY, params, REQUEST_CODE_MY_PROFILE);
            }
        });

        //跳转 myBike页面
        rl_user_menu_myBike.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //关闭所有弹窗
                closeBikeListMenu();
                closeControlBikeMenu();

                Map<String, String> params = new HashMap<>();
                params.put("uid", uid);
                params.put("currentConnectBikeId", currentConnectBikeId);
                activityChange(MY_BIKE_ACTIVITY, params, REQUEST_CODE_MY_BIKE);
            }
        });

        //跳转about页面
        rl_user_menu_about.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                activityChange(ABOUT_ACTIVITY, null, null);
            }
        });

        //跳转Setting页面
        rl_user_menu_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                activityChange(SETTING_ACTIVITY, null, null);
            }
        });

        //跳转到运动数据界面
        rl_user_menu_sport.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> params = new HashMap<>();
                params.put("uid", uid);
                activityChange(SPORT_DATA_ACTIVITY, params, REQUEST_CODE_SPORT_DATA);
            }
        });

        //跳转到debug页面
        rl_user_menu_debug.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(DEBUG_ACTIVITY, null, null);
            }
        });

        // 助力状态列表展示
        iv_home_status.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                openBikePowerMenu();
            }
        });

        // 助力状态改变为B
        iv_home_status_bike.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleDataByBLEUtil.sendDataToDevice("m|1");
                closeBikePowerMenu();
            }
        });

        // 助力状态改变为S
        iv_home_status_smt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleDataByBLEUtil.sendDataToDevice("m|2");
                closeBikePowerMenu();
            }
        });

        // 助力状态改变为E
        iv_home_status_eco.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleDataByBLEUtil.sendDataToDevice("m|3");
                closeBikePowerMenu();
            }
        });

        // 助力状态改变为P
        iv_home_status_pow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleDataByBLEUtil.sendDataToDevice("m|4");
                closeBikePowerMenu();
            }
        });

        // 车锁状态改变
        iv_home_lock.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String lockStatus = tv_home_lock_status.getText().toString();
                // 此时为开锁状态 需要关锁 并断开连接
                if ("unlock".equals(lockStatus)) {
//                    handleDataByBLEUtil.sendDataToDevice("c|l");

                    //已经连接 首先判断是不是之前连接的车辆
                    if (null != connectMarkerKey && !connectMarkerKey.equals(currentDeviceInfos[0])) {
                        //不相同 跳出提示框
                        if (null != changeBikeConnectDialog) {
                            changeBikeConnectDialog.show();
                        }

                    } else {
                        //相同 直接关锁
                        handleDataByBLEUtil.sendDataToDevice("c|l");
                    }

                }
                // 此时为关锁状态 需要连接 并开锁
                if ("lock".equals(lockStatus)) {
//                    handleDataByBLEUtil.sendDataToDevice("c|u");

                    //未连接 直接连接
                    openWaitWindow();

                    //蓝牙搜索 并连接
                    if (null != currentDeviceInfos[0]) {
                        scanBleDevice(currentDeviceInfos[0], currentDeviceInfos[1]);
                    }
                }

                //展示当前标识
                showMarker(scanMarkerKey);
            }
        });

        // 蓝牙连接状态改变
        iv_home_connect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                //判断蓝牙正在连接中
                if (BlueToothAssist.isConnecting) {
                    Toast.makeText(HomeMapActivity.this.getApplicationContext(), ToastConstant.BLE_CONNECTING, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (BlueToothAssist.isConnect) {
                    //已经连接 首先判断是不是之前连接的车辆
                    if (null != connectMarkerKey && !connectMarkerKey.equals(currentDeviceInfos[0])) {
                        //不相同 跳出提示框
                        if (null != changeBikeConnectDialog) {
                            changeBikeConnectDialog.show();
                        }

                    } else {
                        //相同 直接断开连接
                        closeBleDevice();
                    }

                } else {
                    //未连接 直接连接
                    openWaitWindow();

                    //蓝牙搜索 并连接
                    if (null != currentDeviceInfos[0]) {
                        scanBleDevice(currentDeviceInfos[0], currentDeviceInfos[1]);
                    }
                }

                //展示当前标识
                showMarker(scanMarkerKey);
            }
        });

        //设置ListView中每行的单击事件
        lv_search_bike_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                BikeInfoResult bikeInfoResult = bikeInfoList.get(position);

                //移动镜头到当前自行车位置
                moveCameraToCurrentMark(bikeInfoResult.getName());

                //关闭自行车list界面
                closeBikeListMenu();

            }

        });

        //等待搜索结果期间阻隔点击事件
        rl_cover.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        //点击刷新车辆位置按钮
        iv_bike_bike_location.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //刷新车辆信息
                refreshBikeInfo();
            }
        });

        //仪表盘是否展示
        iv_dashboard_state.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ll_dashboard.isShown()){
                    ll_dashboard.setVisibility(View.GONE);
                    iv_dashboard_state.setBackgroundResource(R.drawable.ic_dashboard_show);
                }else {
                    ll_dashboard.setVisibility(View.VISIBLE);
                    iv_dashboard_state.setBackgroundResource(R.drawable.ic_dashboard_hide);
                }
            }
        });
    }

    /**
     * 初始化控件内容
     */
    public void initViewContent() {

        //获得页面跳转后传递过来的uid
        if (null != bundle && null != bundle.getString("uid")) {
            uid = bundle.getString("uid");
            Log.e(TAG, "initViewContent: " + uid);
            //查询用户所有信息
            new GetJsonFromWebJob(WebConstant.GET_USER_INFO_PATH + uid, WebConstant.GET, null, REQUEST_SIGN_GET_USER_INFO_BY_UID, HomeMapActivity.this).start();

            //查找用户的所有自行车
            new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO, HomeMapActivity.this).start();

        }
    }

    /**
     * 初始化改变连接车辆弹出框
     */
    private void initChangeBikeConnectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(ToastConstant.DIALOG_NOTICE);
        builder.setMessage(ToastConstant.CHANGE_BIKE_CONNECT_INFO);

        //确定
        builder.setPositiveButton(ToastConstant.DIALOG_CONTINUE, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != dialog) {
                    dialog.dismiss();
                }
                openWaitWindow();

                //首先断开连接
//                closeBleDevice();

                //重新扫描并连接
//                if (null != currentDeviceInfos[0]) {
//                    scanBleDevice(currentDeviceInfos[0], currentDeviceInfos[1]);
//                }

                //直接走关锁流程
                handleDataByBLEUtil.sendDataToDevice("c|l");
            }

        });

        //取消
        builder.setNegativeButton(ToastConstant.DIALOG_CANCEL, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != dialog) {
                    dialog.dismiss();
                }
            }
        });

        changeBikeConnectDialog = builder.create();
    }

    /**
     * 展示用户自定义头像
     */
    private void showUserPortrait() {
        //若用户已选择头像 展示
        String portraitPath = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, SpConstant.USER_PORTRAIT_PATH_KEY + uid);
        if (null == portraitPath || "".equals(portraitPath) || !new File(portraitPath).exists()) {
            Log.e(TAG, "setViewContent: ----------------- 用户头像不存在----------" + portraitPath);
            return;
        }
        iv_user_log.setImageBitmap(BitmapFactory.decodeFile(portraitPath));
    }

    /**
     * 刷新车辆信息
     */
    private void refreshBikeInfo() {
        //断开蓝牙连接
        closeBleDevice();

        //清空地图小标签
        mMap.clear();
        bikeMarkersMap.clear();

        //清空当前所有用户自行车sb
        if (0 != deviceNameSb.length()) {
            deviceNameSb.delete(0, deviceNameSb.length() - 1);
        }

        //重新查找用户的所有自行车
        new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO, HomeMapActivity.this).start();
    }
    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: -----------" + webResult);

        //判断登陆账号名下是否有车
        if (REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO == webSign && !"".equals(webResult)) {
            try {
                bikeInfoResults = gson.fromJson(webResult, BikeInfoResult[].class);
            } catch (Exception e) {
                Log.e(TAG, "dealDataFromWeb: ------ 解析json格式字符串失败");
            }

            bikeInfoList.clear();

            if (bikeInfoResults.length <= 0) {
                Log.e(TAG, "dealDataFromWeb: ----------------------- 名下没有任何车辆");
            } else {
                //如果有车，取到车的信息,展示
                for (BikeInfoResult bikeInfoResult : bikeInfoResults) {
                    bikeInfoList.add(bikeInfoResult);
                    showBikeOnMap(bikeInfoResult);

                    //判断车辆是否报警
                    addAlarmBikeInfo(bikeInfoResult);
                }
            }
            bikeInfoAdapter.notifyDataSetChanged();
            return;
        }

        //获得名下报警车辆信息
        if (REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO_BY_ALARM == webSign && !"".equals(webResult)) {
            try {
                bikeInfoResults = gson.fromJson(webResult, BikeInfoResult[].class);
            } catch (Exception e) {
                Log.e(TAG, "dealDataFromWeb: ------ 解析json格式字符串失败");
            }

            if (bikeInfoResults.length <= 0) {
                Log.e(TAG, "dealDataFromWeb: ----------------------- 名下没有任何车辆");
            } else {
                //如果有车，取到车的信息,展示
                for (BikeInfoResult bikeInfoResult : bikeInfoResults) {
                    //添加报警车辆信息
                    addAlarmBikeInfo(bikeInfoResult);
                }
            }
            return;
        }

        //从服务器获取到用户信息
        if (REQUEST_SIGN_GET_USER_INFO_BY_UID == webSign && !"".equals(webResult)) {
            UserInfoByUidResult userInfoByUidResult = gson.fromJson(webResult, UserInfoByUidResult.class);

            if (null != userInfoByUidResult.getEmail() && !"".equals(userInfoByUidResult.getEmail())) {
                tv_um_email_address.setText(userInfoByUidResult.getEmail());
            }

            tv_um_username.setText("Volta_" + uid);
            if (null != userInfoByUidResult.getUsername() && !"".equals(userInfoByUidResult.getUsername())) {
                tv_um_username.setText(userInfoByUidResult.getUsername());
            }
            return;
        }

        //依据车出厂名从服务器获取到车的Cid 记录该车为当前连接状态 主要用于在自行车页面释放自行车时 判断该车是否正在连接
        if (REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_CURRENT_CONN == webSign) {

            BikeInfoResult bikeInfoResult = gson.fromJson(webResult, BikeInfoResult.class);
            Log.i(TAG, "dealDataFromWeb: ---------------------------------- 获取到当前连接车辆信息" + bikeInfoResult.toString());
            currentConnectBikeId = bikeInfoResult.getId();
            BlueToothAssist.currentConnectBikeId = currentConnectBikeId;

            return;
        }

        //判断账号登出成功
        if (REQUEST_SIGN_LOGOUT == webSign) {
            Log.e(TAG, "dealDataFromWeb: ----------------------------- logout");
            //清除页面，退出app
            ActivitiesStackUtil.getInstance().exit();
            return;
        }

        //上传经纬度
        if (REQUEST_SIGN_CHANGE_BIKE_NICKNAME_BY_CID == webSign && "".equals(webResult)) {
            Log.i(TAG, "dealDataFromWeb: ----------------------------- 上传经纬度成功");
            return;
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 跳转页面结果回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //自自行车页面返回
                case REQUEST_CODE_MY_BIKE:
                    Bundle myBikeBundle = data.getExtras();
                    if (null == myBikeBundle || "false".equals(myBikeBundle.getString(ActivityChangeConstant.ACTIVITY_CHANGE_MY_BIKE_ACT_KEY))) {
                        Log.e(TAG, "onActivityResult: --------------------- 没做任何事情");
                        return;
                    }

                    drawer.closeDrawer(Gravity.START);

                    //刷新车辆信息
                    refreshBikeInfo();
                    break;

                //自修改用户信息界面返回
                case REQUEST_CODE_MY_PROFILE:
                    //重新请求用户信息
                    new GetJsonFromWebJob(WebConstant.GET_USER_INFO_PATH + uid, WebConstant.GET, null, REQUEST_SIGN_GET_USER_INFO_BY_UID, HomeMapActivity.this).start();
                    break;

                //搜索蓝牙设备页面返回
                case REQUEST_CODE_BLUETOOTH_SEARCH:
                    String searchBikeName = data.getExtras().getString("search_bike_name");
                    String searchBikeNickName = data.getExtras().getString("search_bike_nick_name");
                    if (null == searchBikeName || "".equals(searchBikeName)) {
                        return;
                    }
                    openWaitWindow();

                    //移动镜头到当前自行车位置
                    moveCameraToCurrentMark(searchBikeName);
                    ic_control_bike_menu.setVisibility(View.VISIBLE);
                    scanBleDevice(searchBikeName, searchBikeNickName);
                    break;

                //处理地点搜索数据返回
                case PLACE_AUTOCOMPLETE_REQUEST_CODE:

                    if (resultCode == RESULT_OK) {
                        //返回结果 成功
                        Place place = PlaceAutocomplete.getPlace(this, data);
                        addMarkerToMap(place.getLatLng(), place.getName().toString(), null);

                    } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                        //返回结果 错误
                        Status status = PlaceAutocomplete.getStatus(this, data);
                        Log.i(TAG, status.getStatusMessage());

                    } else if (resultCode == RESULT_CANCELED) {
                        //返回结果 用户取消搜索
                        Log.i(TAG, "onActivityResult: 用户取消搜索");
                    }
                    break;
            }
        }
    }

    /***********************************************************************************************/
    /**                                     自定义私有方法                                         **/
    /***********************************************************************************************/
    /**
     * 搜索蓝牙目标设备
     *
     * @param bikeName     需要蓝牙设备名称 用户自定义名称
     * @param bikeNickName 用户自定义名称
     */
    private void scanBleDevice(String bikeName, String bikeNickName) {

        //判断设备是否支持蓝牙
        if (!handleDataByBLEUtil.judgeDeviceSupportBle()) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.DEVICE_NOT_SUPPORT_BLE, Toast.LENGTH_LONG).show();
        }

        //初始化搜索条件对象
        scanDeviceConditionsDTO = new ScanDeviceConditionsDTO(bikeName, getDeviceAddressFromDeviceName(bikeName));
        if (null != bikeNickName && !"".equals(bikeNickName)) {
            scanDeviceConditionsDTO.setDeviceNickname(bikeNickName);
        }

        //开启蓝牙
        handleDataByBLEUtil.startBluetooth();

        //通过名称连接蓝牙设备
        handleDataByBLEUtil.connectDeviceByNameWithoutScan(bikeName, iConnectCallback);

        //设置车名
        tv_bike_name.setText(null != bikeNickName && !"".equals(bikeNickName) ? bikeNickName : bikeName);
    }

    /**
     * 搜索特定名称设备
     */
    private void repairConnectScan(){
        Log.i(TAG, "scanSpecificNameDevice: 开始断开重连");
        
        if(null == scanDeviceConditionsDTO || null == scanDeviceConditionsDTO.getDeviceAddress()){
            return;
        }

        handleDataByBLEUtil.scanDevices(iScanCallback);
    }

    /**
     * 断开蓝牙
     */
    private void closeBleDevice() {
        //断开连接
        HandleDataByBLEUtil.disConnectDevice();

        setBikeStateDisConnect(connectMarkerKey);
    }

    /**
     * 打开助力状态修改页面
     */
    private void openBikePowerMenu() {
        ll_bike_status_menu.setVisibility(View.VISIBLE);
        rl_device_menu.setVisibility(View.GONE);
//        bike_status = false;
    }

    /**
     * 关闭助力状态修改页面
     */
    private void closeBikePowerMenu() {
        rl_device_menu.setVisibility(View.VISIBLE);
        ll_bike_status_menu.setVisibility(View.GONE);
//        bike_status = true;
    }

    /**
     * 展示当前地图小图标
     */
    private void showMarker(final String markKey) {

        if (null == bikeMarkersMap.get(markKey)) {
            Log.e(TAG, "onReceive: ---------------------- 地图标识为null");
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != bikeMarkersMap.get(markKey)) {
                    bikeMarkersMap.get(markKey).showInfoWindow();
                }
            }
        });
    }

    /**
     * 移动镜头到目标设备位置
     *
     * @param deviceName 设备名称
     */
    private void moveCameraToCurrentMark(String deviceName) {
        if (null == mMap) {
            Log.e(TAG, "onItemClick: 地图未初始化，无法移动地图镜头到当前设备所在经纬度");
            return;
        }

        if (null == bikeMarkersMap.get(deviceName)) {
            Log.e(TAG, "onItemClick: 地图上对应小图标未找到，为空---" + deviceName);
            return;
        }

        Marker targetMarker = bikeMarkersMap.get(deviceName);

        //移动地图镜头
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(targetMarker.getPosition(), 18));

        //展示信息窗口
        bikeMarkersMap.get(deviceName).showInfoWindow();

        //打开控制蓝牙连接窗口
        openControlBikeMenu(targetMarker.getTitle(), targetMarker.getSnippet());
    }

    /**
     * 打开添加自行车页面
     */
    private void openBikeListMenu() {
        if (!ic_add_bike_menu_display_status) {
            ic_add_bike_menu.setVisibility(View.VISIBLE);
            ic_add_bike_menu_display_status = !ic_add_bike_menu_display_status;
        }
    }

    /**
     * 关闭添加自行车页面
     */
    private void closeBikeListMenu() {
        if (ic_add_bike_menu_display_status) {
            ic_add_bike_menu.setVisibility(View.GONE);
            ic_add_bike_menu_display_status = !ic_add_bike_menu_display_status;
        }
    }

    /**
     * 打开控制自行车页面
     */
    private void openControlBikeMenu(String bikeName, String bikeNickName) {
        isDeviceNotChange = false;

        //使连接按钮可按
        currentDeviceInfos[0] = bikeName;
        currentDeviceInfos[1] = bikeNickName;

        if (null == bikeName) {
            return;
        }

        //点击图标为当前连接的设备
        if (bikeName.equals(connectMarkerKey)) {
            tv_bike_state.setText("connect");
            iv_bike_connect_status.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_connect));

            tv_home_connect_status.setText("conn");
        } else {
            //点击图标不是当前连接的设备
            tv_bike_state.setText("disconnect");

            iv_bike_connect_status.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_disconnect));
            pb_bike_electricity.setProgress(0);
            tv_bike_electric_amount.setText("0%");

            tv_home_connect_status.setText("disc");
            tv_home_lock_status.setText("lock");
            iv_home_lock.setImageResource(R.drawable.selector_home_on_lock);
        }

        tv_bike_name.setText(null == bikeNickName || "".equals(bikeNickName) ? bikeName : bikeNickName);

        if (!ic_control_bike_menu_display_status) {
            Log.w(TAG, "openControlBikeMenu: ------------------ 展示控制车辆界面");
            ic_control_bike_menu.setVisibility(View.VISIBLE);
            ic_control_bike_menu_display_status = true;
        }

        //判断车辆是不是简版Volta 并以此判断仪表盘呼出按钮是否展示
        if(bikeName.contains("vta")) {
            iv_dashboard_state.setVisibility(View.GONE);
            ll_home_status_smt.setVisibility(View.VISIBLE);
//            ll_home_status_eco.setVisibility(View.VISIBLE);
        } else if(bikeName.contains("vtb")){
            iv_dashboard_state.setVisibility(View.VISIBLE);
            ll_home_status_smt.setVisibility(View.GONE);
//            ll_home_status_eco.setVisibility(View.GONE);
        }
    }

    /**
     * 关闭控制自行车页面
     */
    private void closeControlBikeMenu() {
        if (ic_control_bike_menu_display_status) {
            ic_control_bike_menu.setVisibility(View.GONE);
            ic_control_bike_menu_display_status = false;
        }
    }

    /**
     * 更新 展示名下自行车名称 的ListView内容
     *
     * @param br 依靠 cid 获取的车辆详细信息
     */
    private void showBikeOnMap(BikeInfoResult br) {
        String deviceName = br.getName();

        if (null == deviceName) {
            return;
        }

        if (null == br.getLat() || null == br.getLng()) {
            Log.e(TAG, "dealDataFromWeb: 从网络获取到的自行车具体信息其地址为空---" + br.getName());

            if (null == currentLocation) {
                return;
            }

            //如果没有位置信息 随机指定手机周围的位置
            double x = Math.random() / 1000;
            double y = Math.random() / 1000;
            bikeMarkersMap.put(deviceName, addBikeMarkerToMap(currentLocation.getLatitude() + x + "", currentLocation.getLongitude() + y + "", deviceName, br.getNickname()));
        } else {
            //在地图上添加Marker标识 并将其添加到Marker集合中
            bikeMarkersMap.put(deviceName, addBikeMarkerToMap(br.getLat(), br.getLng(), deviceName, br.getNickname()));
        }

        //判断用户名下的车中 是否有上一次连接的车的名字 如果有，直接跳到当前车辆图标处
        if (deviceName.equals(historyConnectBikeName)) {
            Log.i(TAG, "showBikeOnMap: ------------------------------------- 跳转到历史车辆图标并连接 历史车辆名称 " + deviceName);
            showMarkerKey = deviceName;
            openControlBikeMenu(deviceName, br.getNickname());
            showMarker(deviceName);
//            scanBleDevice(deviceName, br.getNickname());
        }

        bikeInfos.put(br.getName(), null == br.getNickname() || "".equals(br.getNickname()) ? "#$%&**" : br.getNickname());
    }

    /**
     * 从自行车名称中得到获得设备Mac地址的64位编码并将其解密
     *
     * @param deviceName 设备名称
     * @return 获取到的部分地址
     */
    private String getDeviceAddressFromDeviceName(String deviceName) {
        String base64MacAddress = deviceName.split("_")[1];

        return EncryptStringUtil.customBase64Decode(base64MacAddress);
    }

    /**
     * 设置为断开连接
     */
    private void setBikeStateDisConnect(String bikeName) {
        tv_bike_state.setText("disconnect");

        iv_bike_connect_status.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_disconnect));
        pb_bike_electricity.setProgress(0);
        tv_bike_electric_amount.setText("0%");

        tv_home_connect_status.setText("disc");
        tv_home_lock_status.setText("lock");
        iv_home_lock.setImageResource(R.drawable.selector_home_on_lock);

        showMarker(bikeName);

        //更改车辆状态 断开连接
        setBikeStateForList(bikeName, BluetoothDeviceConstant.STATE_DISCONNECT);

        //更改辅助状态参数
        connectMarkerKey = "";
        BlueToothAssist.isUnlock = false;
        BlueToothAssist.isConnect = false;
        BlueToothAssist.connectDeviceName = "";
        BlueToothAssist.currentConnectBikeId = "";
    }

    /**
     * 打开等待窗
     */
    private void openWaitWindow() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //开启等待框
                rl_cover.setVisibility(View.VISIBLE);

                //开启连接超时定时线程
                BlueToothAssist.isConnecting = true;
            }
        });
    }

    /**
     * 关闭等待窗
     */
    private void closeWaitWindow() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //关闭等待窗
                BlueToothAssist.isConnecting = false;
                rl_cover.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 开启相关线程
     */
    private void openBatteryAndLocationThread() {
        //开启查询电量定时器
        elecTimingThreadUtil.openThread(TimingConstant.ELECTRIC_THREAD_NAME, TimingConstant.ELECTRIC_TIME);

        //开启上报位置定时器
        locationTimingThreadUtil.openThread(TimingConstant.BIKE_LOCATION_THREAD_NAME, TimingConstant.BIKE_LOCATION_TIME);
    }

    /**
     * 关闭相关线程
     */
    private void closeBatteryAndLocationThread() {
        //关闭查询电量定时器
        elecTimingThreadUtil.closeThread(TimingConstant.ELECTRIC_THREAD_NAME);
        //关闭上报位置定时器
        locationTimingThreadUtil.closeThread(TimingConstant.BIKE_LOCATION_THREAD_NAME);
    }

    /**
     * 设置车辆状态
     * @param bikeName 车辆名车
     * @param bikeState 车辆状态
     */
    private void setBikeStateForList(String bikeName, String bikeState){
        if(null == bikeName || null == bikeState){
            return;
        }

        for (BikeInfoResult bikeInfoResult:bikeInfoList){
            if(bikeName.equals(bikeInfoResult.getName())){

                if(bikeState.equals(bikeInfoResult.getState())){
                    return;
                }
                bikeInfoResult.setState(bikeState);
            }
        }

        bikeInfoAdapter.notifyDataSetChanged();
    }

    /**
     * 监听回退按钮事件
     */
    @Override
    public void onBackPressed() {
        double lastPressTime = System.currentTimeMillis();

        if (lastPressTime - firstPressTime < 2000) {

            //告诉服务器端退出登陆
            if (null != uid && !"".equals(uid)) {
                Map<String, String> params = new HashMap<>();
                params.put(WebConstant.LOGOUT_PATH_USER_ID, uid);
                new GetJsonFromWebJob(WebConstant.LOGOUT_PATH, WebConstant.GET, params, REQUEST_SIGN_LOGOUT, HomeMapActivity.this).start();
            }
        }
        firstPressTime = lastPressTime;
        Toast.makeText(this.getApplicationContext(), ToastConstant.EXIST_PRESS_AGAIN, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断车辆是否报警 并记录信息
     * @param bikeInfoResult 车辆数据结果集
     */
    private void addAlarmBikeInfo(BikeInfoResult bikeInfoResult){
        if(AlarmConstant.ALARM_TYPE_NORMAL.equals(bikeInfoResult.getAlert_type())){
            //没有报警
            return;
        }

        //记录报警车辆信息
        alarmAssist.addAlarmInfo(bikeInfoResult.getName(),new AlarmInfoResult(bikeInfoResult.getName(), bikeInfoResult.getNickname(),bikeInfoResult.getAlert_type()));

        if(View.GONE == tv_alarm_prompt.getVisibility()){
            tv_alarm_prompt.setVisibility(View.VISIBLE);
        }
    }
    /***********************************************************************************************/
    /**                                       自定义广播接收者类                                    **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class HomeMapHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            //表明验证通过 可以进行下一步操作
            if (result.contains("^a|")) {

                //更改为已连接状态
                tv_home_connect_status.setText("conn");

                tv_bike_state.setText("connect");
                iv_bike_connect_status.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_connect));

                //设置当前连接设备名称
                connectMarkerKey = scanDeviceConditionsDTO.getDeviceName();

                //获取当前连接的车辆名称对应的车辆id
                Map<String, String> map = new HashMap<>();
                map.put("name", scanDeviceConditionsDTO.getDeviceName());
                new GetJsonFromWebJob(WebConstant.FIND_BIKE_BY_NAME_PATH, WebConstant.POST, map, REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_CURRENT_CONN, HomeMapActivity.this).start();

                BlueToothAssist.connectDeviceName = scanDeviceConditionsDTO.getDeviceName();

                //将当前连接的自行车名称存储到sp中
                Map<String, String> spParams = new HashMap<>();
                spParams.put(SpConstant.HISTORY_CONNECT_BIKE_NAME_KEY, scanDeviceConditionsDTO.getDeviceName());
                handleDataBySharePreferencesUtil.putDateIntoSharePre(SpConstant.SP_NAME, spParams);

                //改变小图标为连接
                Marker marker = bikeMarkersMap.get(scanDeviceConditionsDTO.getDeviceName());
                Log.e(TAG, "onReceive: --------------------- 连接到设备：" + scanDeviceConditionsDTO.getDeviceName() + "----当前连接：" + connectMarkerKey);
                if (null == marker) {
                    Log.e(TAG, "onReceive: 当前连接自行车的地图上的小图标 不存在");
                    return;
                }
                marker.showInfoWindow();

                //移动镜头到当前自行车位置
                moveCameraToCurrentMark(scanDeviceConditionsDTO.getDeviceName());

                //查询是否锁车
//                handleDataByBLEUtil.sendDataToDevice("c|r");
                isBatteryAfterLock = false;

                //改变蓝牙辅助类参数
                BlueToothAssist.isConnect = true;

                //连接成功 自动开锁
                handleDataByBLEUtil.sendDataToDevice("c|u");

                closeWaitWindow();
                return;
            }

            //改变电池电量progressBar
            if (result.contains("^i|")) {

                //判断展示框是不是当前连接车辆 借此确定是否展示电量信息
                if(null != connectMarkerKey && !connectMarkerKey.equals(currentDeviceInfos[0])){
                    return;
                }

                String[] params = result.replace("^i|", "").replace("$", "").split(",");

                //设置电量
                pb_bike_electricity.setProgress(Integer.parseInt(params.length > 0 ? params[0] : "0"));
                tv_bike_electric_amount.setText((params.length > 0 ? params[0] : "0") + "%");

                //设置骑行模式
                switch (params.length > 1 ? params[1] : "0") {
                    case "0":
                        Log.i(TAG, "onReceive: ---------------------- 没取到模式");
                        break;
                    case "1":
                        iv_home_status.setImageResource(R.drawable.selector_home_m_b);
                        break;
                    case "2":
                        iv_home_status.setImageResource(R.drawable.selector_home_m_s);
                        break;
                    case "3":
                        iv_home_status.setImageResource(R.drawable.selector_home_m_e);
                        break;
                    case "4":
                        iv_home_status.setImageResource(R.drawable.selector_home_m_p);
                        break;
                }
                return;
            }

            //改变助力模式为BIKE
            if (result.contains("m|1")) {
                iv_home_status.setImageResource(R.drawable.selector_home_m_b);
                return;
            }

            //改变助力模式为SMT
            if (result.contains("m|2")) {
                iv_home_status.setImageResource(R.drawable.selector_home_m_s);
                return;
            }

            //改变助力模式为ECO
            if (result.contains("m|3")) {
                iv_home_status.setImageResource(R.drawable.selector_home_m_e);
                return;
            }

            //改变助力模式为POW
            if (result.contains("m|4")) {
                iv_home_status.setImageResource(R.drawable.selector_home_m_p);
                return;
            }

            //初始化车锁状态
            if (result.contains("^c|r")) {
                String lightState = result.replace("^c|", "").replace("$", "");

                //关锁
                if ("l".equals(lightState)) {
                    iv_home_lock.setImageResource(R.drawable.selector_home_on_lock);
                    tv_home_lock_status.setText("lock");

                    //关闭相关线程
                    closeBatteryAndLocationThread();

                    //改变蓝牙辅助类参数
                    BlueToothAssist.isUnlock = false;
                    return;
                }

                //开锁
                if ("u".equals(lightState) && !isBatteryAfterLock) {
                    iv_home_lock.setImageResource(R.drawable.selector_home_off_lock);
                    tv_home_lock_status.setText("unlock");

                    //改变蓝牙辅助类参数
                    BlueToothAssist.isUnlock = true;

                    //开启相关线程
                    openBatteryAndLocationThread();
                    return;
                }
            }

            //改变车为关锁的状态
            if (result.contains("c|l")) {
                iv_home_lock.setImageResource(R.drawable.selector_home_on_lock);
                tv_home_lock_status.setText("lock");

                //关闭相关线程
                closeBatteryAndLocationThread();

                //展示当前地图图标
                showMarker(connectMarkerKey);

                //改变蓝牙辅助类参数
                BlueToothAssist.isUnlock = false;

                //修改查询锁状态指令为正常
                isBatteryAfterLock = false;

                //更改车辆状态 关锁
                setBikeStateForList(connectMarkerKey, BluetoothDeviceConstant.STATE_LOCK);

                //断开连接
                closeBleDevice();

                return;
            }

            //改变车为开锁的状态
            if (result.contains("c|u")) {
                showMarker(connectMarkerKey);

                //更改车辆状态 开锁
                setBikeStateForList(connectMarkerKey, BluetoothDeviceConstant.STATE_UNLOCK);

                //判断是正常查询车锁信息还是电量定时器查询车锁状态
                if (isBatteryAfterLock) {

                    //判断展示框是不是当前连接车辆 不是 取消接下来的操作
                    if(null != connectMarkerKey && !connectMarkerKey.equals(currentDeviceInfos[0])){
                        return;
                    }

                    iv_home_lock.setImageResource(R.drawable.selector_home_off_lock);
                    tv_home_lock_status.setText("unlock");

                    handleDataByBLEUtil.sendDataToDevice("i");
                    return;
                }

                iv_home_lock.setImageResource(R.drawable.selector_home_off_lock);
                tv_home_lock_status.setText("unlock");

                //开启相关线程
                openBatteryAndLocationThread();

                //将sp中骑行距离重置为0 并记录当前时间
                Map<String, String> params = new HashMap<>();
                params.put("mileage", "0");
                params.put("sdCurrentTime", SystemClock.currentThreadTimeMillis() / 1000 + "");
                handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, params);

                //改变蓝牙辅助类参数
                BlueToothAssist.isUnlock = true;
                return;
            }

            if ("bluetooth disconnect".equals(result)) {
                Log.e(TAG, "onReceive: ------------ 断开与设备连接");
                setBikeStateDisConnect(connectMarkerKey);
                return;
            }

            //改变连接状态
            if ("connect".equals(result)) {
                Log.w(TAG, "onReceive: ------------- 蓝牙已连接");
                return;
            }

            if (result.contains("Send instruct failure")) {
                Toast.makeText(context.getApplicationContext(), result, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 接收到车辆报警信息的广播接收者
     */
    class HomeMapAlarmMessageReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            AlarmAssist.isAlarm = false;
            //查询用户名下所有自行车
            new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO_BY_ALARM, HomeMapActivity.this).start();
        }
    }
    /***********************************************************************************************/
    /**                                       自定义BaseAdapter方法                                **/
    /***********************************************************************************************/

    /**
     * 自定义缓存复用类
     */
    class ViewHolder {
        ImageView iv_bike_connect_state;
        TextView tv_lv_bike_name;
    }

    /**
     * 自定义BaseAdapter
     */
    class BikeInfoAdapter extends BaseAdapter {

        private ViewHolder viewHolder;

        @Override
        public int getCount() {
            return bikeInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return bikeInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return bikeInfoList.get(position).hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(HomeMapActivity.this);
            BikeInfoResult bikeInfoResult = bikeInfoList.get(position);

            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_bike_list_info, null);
                viewHolder = new ViewHolder();
                viewHolder.iv_bike_connect_state = (ImageView) convertView.findViewById(R.id.iv_bike_list_info_connect_state);
                viewHolder.tv_lv_bike_name = (TextView) convertView.findViewById(R.id.tv_bike_list_info_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            //设置车的名称
            viewHolder.tv_lv_bike_name.setText((null == bikeInfoResult.getNickname() || "".equals(bikeInfoResult.getNickname())) ? bikeInfoResult.getName() : bikeInfoResult.getNickname());

            //设置车辆状态
            String bikeState = bikeInfoResult.getState();

            //未连接
            if(null == bikeState || "".equals(bikeState)){
                //为空 直接设置未连接
                viewHolder.iv_bike_connect_state.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_marker_disc));
            }else{
                switch (bikeState){
                    case BluetoothDeviceConstant.STATE_DISCONNECT:
                        viewHolder.iv_bike_connect_state.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_marker_disc));
                        break;
                    case BluetoothDeviceConstant.STATE_CONNECT:
                        viewHolder.iv_bike_connect_state.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_marker_lock));
                        break;
                    case BluetoothDeviceConstant.STATE_LOCK:
                        viewHolder.iv_bike_connect_state.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_marker_lock));
                        break;
                    case BluetoothDeviceConstant.STATE_UNLOCK:
                        viewHolder.iv_bike_connect_state.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_bike_marker_con));
                        break;
                }
            }

            return convertView;
        }
    }

    /***********************************************************************************************/
    /**                                            自定义定时线程                                  **/
    /***********************************************************************************************/
//    private void startSearchThread() {
//        currentThreadCode++;
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                int recordNum = currentThreadCode;
//                SystemClock.sleep(10000);
//                Log.w(TAG, "run: ---------------------- 等待线程 " + BlueToothAssist.isConnecting + "-------currentThreadCode " + currentThreadCode + "-------recordNum " + recordNum);
//                if (BlueToothAssist.isConnecting && (currentThreadCode == recordNum)) {
//                    BlueToothAssist.isConnecting = false;
//                    handleDataByBLEUtil.disConnectDevice();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            rl_cover.setVisibility(View.GONE);
//                            Toast.makeText(HomeMapActivity.this.getApplicationContext(), ToastConstant.BLE_CONNECT_TIME_OUT, Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//            }
//        }).start();
//    }
}
